package com.pingan.glue.gluegame.aip.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pingan.glue.gluegame.aip.APIService;
import com.pingan.glue.gluegame.aip.domain.*;
import com.pingan.glue.gluegame.controller.DemoController;
import com.pingan.glue.gluegame.http.GlueGameClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("baidu")
public class BaiDuAPIServiceImpl implements APIService {

    private final static Logger LOGGER = LoggerFactory.getLogger(BaiDuAPIServiceImpl.class);

    private static final String LIVENESS_CONTROL="NONE";
    private static final String QUALITY_CONTROL="LOW";
    private static final String IMAGES_TYPE="BASE64";

    private static final String URL_TOKEN="/token?";
    private static final String URL_FACE_ADD="/face/v3/faceset/user/add?access_token=";
    private static final String URL_FACE_UPDATE="/face/v3/faceset/user/update?access_token=";
    private static final String URL_FACE_DELETE="/face/v3/faceset/face/delete?access_token=";

    private static final String URL_FACE_DETECT="/face/v3/detect?access_token=";
    private static final String URL_FACE_SEARCH="/face/v3/search?access_token=";


    private static final String FACE_FIELD="age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,eye_status,emotion,face_type";
    private static final String FACE_TYPE_LIVE="LIVE";


    //@Value("glue.game.api.client.id")
    private String clientId = "llLc1lGzxBI1lbuwvGKv2Alr";
    //@Value("glue.game.api.client.secret")
    private String clientSecret = "CTSNTMewTZr3l53OeFtYCB7rWGH1GVHu";  //百度AI账号获取
    //@Value("glue.game.api.url")
    private String authUrl="https://aip.baidubce.com/oauth/2.0";

    private String faceUrl ="https://aip.baidubce.com/rest/2.0";

    @Resource
    private GlueGameClient glueGameClient;

    @Override
    public String auth() {
        String getAccessTokenUrl = authUrl +URL_TOKEN
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + clientId
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + clientSecret;
        JSONObject res = glueGameClient.get(getAccessTokenUrl);
        return res.getString("access_token");
    }

    @Override
    public JSONObject add(FaceAddDto dto) {

        return faceAddOrUpdate(dto, URL_FACE_ADD);
    }

    @Override
    public JSONObject update(FaceAddDto dto) {
        return faceAddOrUpdate(dto, URL_FACE_UPDATE);
    }

    private JSONObject faceAddOrUpdate(FaceAddDto dto, String addOrUpdate) {
        //dto.setImage_type(IMAGES_TYPE);
        dto.setLiveness_control(LIVENESS_CONTROL);
        dto.setQuality_control(QUALITY_CONTROL);
        JSONObject json = glueGameClient.post(faceUrl + addOrUpdate, auth(), (JSONObject) JSONObject.toJSON(dto));
        return json;
    }

    public String faceDelete(FaceAddDto dto) {
        JSONObject json = glueGameClient.post(faceUrl + URL_FACE_DELETE, auth(), (JSONObject) JSONObject.toJSON(dto));
        return json == null ? null : json.toJSONString();
    }

    @Override
    public FaceFieldDto detect(String image) {
        FaceDetectDto dto = new FaceDetectDto();
        dto.setImage(image);
        dto.setImage_type(IMAGES_TYPE);
        dto.setFace_field(FACE_FIELD);
        dto.setFace_type(FACE_TYPE_LIVE);
        dto.setMax_face_num("1");
        JSONObject json = glueGameClient.post(faceUrl+URL_FACE_DETECT,auth(),(JSONObject)JSONObject.toJSON(dto));
        if (json ==null){
            return null;
        }
        String error = json.getString("error_code");
        if (!StringUtils.equals("0",error)){
            LOGGER.info("BaiDuAPIServiceImpl_detect_error:{}",json.toJSONString());
            return null;
        }
        JSONArray ja = json.getJSONObject("result").getJSONArray("face_list");
        return JSONObject.toJavaObject((JSON)ja.get(0),FaceFieldDto.class);
    }

    @Override
    public AIPResponse search(FaceSearchDto dto) {

        JSONObject json = glueGameClient.post(faceUrl+URL_FACE_SEARCH,auth(),(JSONObject)JSONObject.toJSON(dto));
        return json==null?null:JSONObject.toJavaObject(json,AIPResponse.class);
    }

}
